package com.lovo.service.impl;

import com.lovo.dao.UserDAO;
import com.lovo.dao.impl.UserDAOImpl;
import com.lovo.pojo.UsersDO;
import com.lovo.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UsersDO getByUsernameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username, pwd);
    }

    @Override
    public UsersDO getById(int id) {
        return userDAO.getById(id);
    }

    @Override
    public void saveMoney(int id, double blance) {
        UsersDO users = userDAO.getById(id);
        users.setBlance(users.getBlance() + blance);
        userDAO.update(users);
    }

    @Override
    public void getMoney(int id, double blance) throws Exception {
        UsersDO users = userDAO.getById(id);
        if (users.getBlance() < blance) {
            throw new Exception("余额不足");
        }
        users.setBlance(users.getBlance() - blance);
        userDAO.update(users);
    }

    @Override
    public void transferAccounts(String otherName, double blance, int id) throws Exception {
        UsersDO otherUsers = userDAO.getByName(otherName);//转账给的那个人的账户
        UsersDO users = userDAO.getById(id);//本人账户
        if (users.getBlance() < blance) {
            throw new Exception("当前账户余额不足");
        }
        if (otherUsers == null) {
            throw new Exception("查无此人");
        }
        if (otherUsers.getUserName().equals(users.getUserName())) {
            throw new Exception("不能转账给自己");
        }
        users.setBlance(users.getBlance() - blance);
        otherUsers.setBlance(otherUsers.getBlance() + blance);
        userDAO.update(users, otherUsers);
    }

    @Override
    public void changePwd(String oldPwd, String newPwd, int id) throws Exception {
        UsersDO users = userDAO.getById(id);//本人账户
        if (!oldPwd.equals(users.getPwd())) {
            throw new Exception("密码输入错误");
        }
        if (oldPwd.equals(newPwd)) {
            throw new Exception("新旧密码不能一致");
        }
        users.setPwd(newPwd);
        userDAO.update(users);
    }

}
